package com.group7.mall.util;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.group7.mall.bean.SimilarImageResult;
import com.group7.mall.req.BaiduImageRequest;
import com.group7.mall.resp.SimilarImageResponse;
import org.json.JSONObject;
import okhttp3.*;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;

public class BaiduSimilarImageServerUtils {

    public static final String API_KEY = "BVCpHzanyljJ3L17WWFAFMlK";
    public static final String SECRET_KEY = "GtoeCvG2x2jjfhm1KHCsir31A9m8VVMk";

    static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();

    static String getAccessToken() throws IOException {
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType, "grant_type=client_credentials&client_id=" + API_KEY
                + "&client_secret=" + SECRET_KEY);
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/oauth/2.0/token")
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        return new JSONObject(response.body().string()).getString("access_token");
    }

    public static int addImage(BaiduImageRequest baiduImageRequest) throws IOException {
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType, "brief="+baiduImageRequest.getBrief() +"&url="
                +baiduImageRequest.getImageUrl());
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/rest/2.0/image-classify/v1/realtime_search/similar/add?access_token=" + getAccessToken())
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        if(response.isSuccessful()) {
            String jsonString = response.body().string(); // 读取响应体为字符串
            Gson gson = new Gson();
            JsonObject jsonObject = gson.fromJson(jsonString, JsonObject.class); // 解析JSON字符串为JsonObject
            if (jsonObject.has("error_code")) { // 检查是否存在error_code字段
                int errorCode = jsonObject.get("error_code").getAsInt(); // 提取error_code字段的值
                System.out.println("Error Code: " + errorCode);
                return errorCode;
            }
            return 200;
        } else {
            return -1;
        }
    }

    public static int updateImage(BaiduImageRequest baiduImageRequest) throws IOException {
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType, "url="+baiduImageRequest.getImageUrl()
                +"&brief="+baiduImageRequest.getBrief());
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/rest/2.0/image-classify/v1/realtime_search/similar/update?access_token=" + getAccessToken())
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        if(response.isSuccessful()) {
            String jsonString = response.body().string(); // 读取响应体为字符串
            Gson gson = new Gson();
            JsonObject jsonObject = gson.fromJson(jsonString, JsonObject.class); // 解析JSON字符串为JsonObject
            if (jsonObject.has("error_code")) { // 检查是否存在error_code字段
                int errorCode = jsonObject.get("error_code").getAsInt(); // 提取error_code字段的值
                System.out.println("Error Code: " + errorCode);
                return errorCode;
            }
            return 1;
        } else {
            return -1;
        }
    }

    public static SimilarImageResponse searchSimilarImageBrief(BaiduImageRequest baiduImageRequest) throws IOException {
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        String requestBody = "";
        baiduImageRequest.setPageNo((baiduImageRequest.getPageNo() - 1) * baiduImageRequest.getPageSize());
        System.out.println(baiduImageRequest.getPageNo() + " " + baiduImageRequest.getPageSize());
        if (baiduImageRequest.getImageBase64() != null) {
            try {
                String urlEncodedBase64Image = URLEncoder.encode(baiduImageRequest.getImageBase64(), StandardCharsets.UTF_8.name());
                requestBody = "image=" + urlEncodedBase64Image +
                        "&rn=" + baiduImageRequest.getPageSize() + "&pn=" + baiduImageRequest.getPageNo();
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        } else if(baiduImageRequest.getImageUrl() != null) {
            requestBody = "url="+baiduImageRequest.getImageUrl()+
                    "&rn="+baiduImageRequest.getPageSize() + "&pn=" + baiduImageRequest.getPageNo();
        } else {
            return null;
        }
        String urlEncodedBase64Image = URLEncoder.encode(baiduImageRequest.getImageBase64(), StandardCharsets.UTF_8.name());
        requestBody = "image=" + urlEncodedBase64Image +
                "&rn=" + baiduImageRequest.getPageSize() + "&pn=" + baiduImageRequest.getPageNo();
        RequestBody body = RequestBody.create(mediaType, requestBody);
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/rest/2.0/image-classify/v1/realtime_search/similar/search?access_token=" + getAccessToken())
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        if(response.isSuccessful()) {
            SimilarImageResponse<SimilarImageResult> similarImageResponse = new SimilarImageResponse<>();
            List<SimilarImageResult> similarImageResultList = new ArrayList<>();
            String jsonString = response.body().string(); // 读取响应体为字符串
            Gson gson = new Gson();
            JsonParser parser = new JsonParser();
            JsonObject jsonObject = gson.fromJson(jsonString, JsonObject.class); // 解析JSON字符串为JsonObject
            if (jsonObject.has("error_code")) { // 检查是否存在error_code字段
                int errorCode = jsonObject.get("error_code").getAsInt(); // 提取error_code字段的值
                System.out.println("Error Code: " + errorCode);
            }
            int resultNum = jsonObject.get("result_num").getAsInt(); // uint32类型在Java中通常使用int表示
//            similarImageResponse.set(resultNum);
            JsonArray resultArray = jsonObject.get("result").getAsJsonArray(); // 结果数组
            // 遍历结果数组，提取每个结果中的参数
            for (int i = 0; i < resultArray.size(); i++) {
                SimilarImageResult similarImageResult = new SimilarImageResult();
                JsonObject resultObj = resultArray.get(i).getAsJsonObject();
                similarImageResult.setContSign(resultObj.get("cont_sign").getAsString());
                similarImageResult.setScore(resultObj.get("score").getAsFloat());
                similarImageResult.setBrief(resultObj.get("brief").getAsString());
                similarImageResultList.add(similarImageResult);
            }
            similarImageResponse.setResult(similarImageResultList);
            return similarImageResponse;
        } else {
            return null;
        }
    }

    public static int deleteImage(BaiduImageRequest baiduImageRequest) throws IOException {
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType, "url="+baiduImageRequest.getImageUrl());
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/rest/2.0/image-classify/v1/realtime_search/similar/delete?access_token=" + getAccessToken())
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        if(response.isSuccessful()) {
            return 1;
        } else {
            return -1;
        }
    }
}
